//
//  WBUserAccount.swift
//  个人微博
//
//  Created by 任聪聪 on 2017/12/15.
//  Copyright © 2017年 任孜聪. All rights reserved.
//

import UIKit
fileprivate let accountFile: NSString = "userAccount.json"
//用户账户信息类
class WBUserAccount: NSObject {
    //登录令牌
    var access_token:String? //= "2.00_dJMZDgzJ_ICc95e3a60ef8rodLB"
    //	access_token的生命周期，单位是秒数。
    //  应用程序默认3年，使用者默认3天
    var expires_in:TimeInterval = 0{
        didSet{
            expires_date = Date(timeIntervalSinceNow: expires_in)
        }
    }
    //过期日期
    var expires_date: Date?
    // 用户id
    var uid:String? = "6112650844"
    //用户头像地址（大图），180×180像素
    var avatar_large:String?
    //用户昵称
    var screen_name:String?
    override var description: String{
        return yy_modelDescription()
    }
    override init() {
        super.init()
        //将磁盘数据加载出来
        //1.获取磁盘路径
        //2.获取二进制数据
        //3.将二进制数据饭序列化
        guard let path = accountFile.cz_appendDocumentDir(),let data = NSData(contentsOfFile: path),
        let dict = try? JSONSerialization.jsonObject(with: data as Data, options: [])else {
            return
        }
        //设置模型数据值
        yy_modelSet(with: dict as! [String : AnyObject])
        //判断accessToken是否过期
        //compare()方法返回结果值（-1）左参数小于右参数，（0）两个参数相等，（1）左参数大于右参数
        //expires_date = Date(timeIntervalSinceNow: -3600*24)
        if (expires_date?.compare(Date()).rawValue)!<0{
            print("用户过期，请重新登录\(self)")
            //用户过期删除沙盒中用户数据
            uid = nil
            access_token = nil
            try? FileManager.default.removeItem(atPath: path)
        }
    }
    //设置用户配置文件到本地方法
    func saveUserAccount() {
        //1.将模型转换为字典　
        var userList = yy_modelToJSONObject() as? [String:AnyObject]
        //删除其中的expires_in 因为增这个变量是个递减的数值不能保持不变，所以要删除
        userList?.removeValue(forKey: "expires_in")
        //2.将字典序列化成json
        guard let data = try? JSONSerialization.data(withJSONObject: userList, options: []), let filePath = (accountFile as NSString).cz_appendDocumentDir()else {
            return
        } 
        //3.写入磁盘
        (data as NSData).write(toFile: filePath, atomically: true)
        print("成功写入磁盘\(filePath)")
    }
}
